package com.woniuxy.portal.service.impl;

import com.woniuxy.portal.common.constant.RedisConstant;
import com.woniuxy.portal.entity.Booktype;
import com.woniuxy.portal.mapper.BooktypeMapper;
import com.woniuxy.portal.model.vo.BookTypeVo;
import com.woniuxy.portal.service.IBooktypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者
 * @since 2023-09-15
 */
@Service
public class BooktypeServiceImpl extends ServiceImpl<BooktypeMapper, Booktype> implements IBooktypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<BookTypeVo> findBookTypes() {

        // 判断：如果redis中没有这个key，就查询数据库
        if (!redisTemplate.hasKey(RedisConstant.BOOK_TYPE_LIST)) {
            // 查询数据库
            List<Booktype> list = baseMapper.selectList(null);
            List<BookTypeVo> result = list.stream().map(booktype -> new BookTypeVo(booktype.getId(), booktype.getName())).collect(Collectors.toList());
            // 查询的结果放入Redis
            redisTemplate.opsForList().leftPushAll(RedisConstant.BOOK_TYPE_LIST, result);
            return result;
        }
         // 从Redis中获取数据
        List resultList = redisTemplate.opsForList().range(RedisConstant.BOOK_TYPE_LIST, 0, -1);

        return resultList;
    }
}
